import { View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useCreation } from "ahooks";

import useFetch from "@/hooks/useFetch";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import ByIcon from "@/components/ui/ByIcon";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import Folding from "@/components/app/Folding";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import ByCellGroup from "@/components/ui/ByCellGroup";
import ByImageGroup from "@/components/ui/ByImageGroup";

import ApiInspection from "@/api/inspection";
import { ensureCompleteUrl } from "@/utils";

import { InspectionStandardContent } from "@/types/Inspection";

const cellProps = {
  size: "small",
  border: true,
  labelWidth: "5em",
} as const;

const StandardOption = ({ source }: { source: any }) => {
  const qualifiedResult = source.options.find((e) => e.isCheck);

  return (
    <View className="mb-3">
      <View className="p-2">{source.quesName}</View>

      <View className="p-2 bg-page rounded-md">
        <ByCell label="是否合格" {...cellProps} border={false}>
          {qualifiedResult ? qualifiedResult?.optionsName : "未巡检"}
        </ByCell>
        <ByCell label="备注" {...cellProps}>
          {source.quesRemark}
        </ByCell>
        <ByCell label="照片" {...cellProps}>
          <ByImageGroup urls={source.picList} showEmptyTip />
        </ByCell>
      </View>
    </View>
  );
};

const FoldingFooter = ({
  source,
}: {
  source: { unpass: number; pass: number; remain: number; pics: string[] };
}) => {
  return (
    <ByRow content="between" className="px-3 pb-3">
      <View>
        <ByText type="second" size="sm">
          合格：
        </ByText>
        <ByText type="success">{source?.pass}</ByText>
      </View>

      <View>
        <ByText type="second" size="sm">
          不合格：
        </ByText>
        <ByText type="error">{source?.unpass}</ByText>
      </View>

      <View>
        <ByText type="second" size="sm">
          未检：
        </ByText>
        <ByText type="info">{source?.remain}</ByText>
      </View>
    </ByRow>
  );
};

// 获取统计数据
function getStatistic(list: InspectionStandardContent[]) {
  return list.reduce(
    (obj, { picList, options }) => {
      const option = options.find((e) => e.isCheck);

      if (option) {
        if (option.isQualified) {
          obj.pass += 1;
        } else {
          obj.unpass += 1;
        }
      } else {
        obj.remain += 1;
      }

      obj.pics = [...obj.pics, ...(picList || [])];
      return obj;
    },
    {
      pass: 0,
      unpass: 0,
      remain: 0,
      pics: [] as string[],
    }
  );
}

export default () => {
  const { params } = useRouter();
  const recordMainId = Number(params.id);
  const intentCustomerId = Number(params.intentCustomerId);

  const { loading, data } = useFetch<{
    isCanSee: boolean;
    list: InspectionStandardContent[];
  }>(ApiInspection.inspectionStandardDetail, {
    defaultParams: [{ recordMainId, intentCustomerId }],
  });

  const toRectificat = () => {
    const list: any[] = [];

    data!.list.forEach((item) => {
      item.quesNaireContent.forEach((element) => {
        const flag = element.options.find((e) => !e.isQualified && e.isCheck);

        if (flag) {
          list.push(element);
        }
      });
    });

    Taro.navigateTo({
      url: `/packageProject/pages/inspection/rectification?intentCustomerId=${intentCustomerId}&recordMainId=${recordMainId}`,
      success(res) {
        res.eventChannel.emit("acceptRectificationList", list);
      },
    });
  };

  const statistic = useCreation(() => {
    if (data?.list) {
      return data.list.map((e) => getStatistic(e.quesNaireContent));
    }
    return [];
  }, [data]);

  // 预览图片
  const previewImages = (index) => {
    const urls = statistic[index]["pics"];
    if (urls.length > 0) {
      Taro.previewImage({ urls: urls.map(ensureCompleteUrl) });
    }
  };

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByRow content="center">
            <ByButton
              className=" w-2/5"
              size="large"
              type="warning"
              onClick={() =>
                Taro.navigateTo({
                  url: `/packageProject/pages/fine/apply?intentCustomerId=${intentCustomerId}`,
                })
              }
            >
              罚款
            </ByButton>

            <ByButton
              className="ml-3 w-2/5"
              size="large"
              onClick={toRectificat}
            >
              整改
            </ByButton>
          </ByRow>
        }
      >
        <ByCellGroup className="m-3">
          <ByCell label="业主可见" align="right">
            {data?.isCanSee ? "是" : "否"}
          </ByCell>
        </ByCellGroup>

        <View className="mx-3">
          <ListView loading={loading} isEmpty={!data?.list.length}>
            {data?.list.map((item, index) => (
              <Folding
                className="mb-3"
                defaultFold={true}
                key={item.quesNaireId}
                title={item.quesNaireName}
                slotRight={
                  <ByText
                    type="primary"
                    className="mr-2"
                    onClick={() => previewImages(index)}
                  >
                    <ByIcon name="ImgList" />
                    <ByText size="sm">
                      {statistic[index]["pics"]?.length || 0}
                    </ByText>
                  </ByText>
                }
                slotFooter={<FoldingFooter source={statistic[index]} />}
              >
                {item.quesNaireContent.map((item) => (
                  <StandardOption key={item.quesId} source={item} />
                ))}
              </Folding>
            ))}
          </ListView>
        </View>
      </Page>
    </>
  );
};
